﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Streamsol.Helpers
{
    public static class ObjectHelper
    {
        /// <summary>
        /// Retrieves the value of a property given the name.
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="propertyName">The name of the property to retrieve.</param>
        /// <returns>An object of the property.</returns>
        public static object ExtractPropertyValue(this object obj, string propertyName)
        {
            PropertyInfo field = obj.GetType().GetProperty(propertyName);
            return field.GetValue(obj, null);
        }

        /// <summary>
        /// Retrieves the value of a property given the name and performs an explicit cast.
        /// </summary>
        /// <typeparam name="T">The type of the property.</typeparam>
        /// <param name="obj"></param>
        /// <param name="propertyName">The name of the property to retrieve.</param>
        /// <returns>An object of the property.</returns>
        public static T ExtractPropertyValue<T>(this object obj, string propertyName)
        {
            PropertyInfo field = obj.GetType().GetProperty(propertyName);
            return (T)field.GetValue(obj, null);
        }

        public static void SetPropertyValue(this object obj, string propertyName, object value)
        {
            PropertyInfo field = obj.GetType().GetProperty(propertyName);
            field.SetValue(obj, value, null);
        }
    }
}
